package com.pippin.editor.exception;

import com.pippin.editor.common.Res;
import com.ql.util.express.exception.QLException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> validationExceptions(MethodArgumentNotValidException ex, WebRequest request) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return new ResponseEntity<>(Res.ERROR(errors.toString()), HttpStatus.OK);
    }

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<Object> runtimeException(RuntimeException ex, WebRequest request) {
        log.error("{} 执行异常", request.getDescription(false), ex);
        return new ResponseEntity<>(Res.ERROR(ex.getMessage()), HttpStatus.OK);
    }


    @ExceptionHandler(QLException.class)
    public ResponseEntity<Object> qLExceptionException(QLException ex, WebRequest request) {
        log.error("{} 执行异常", request.getDescription(false), ex);
        return new ResponseEntity<>(Res.ERROR(ex.getMessage()), HttpStatus.OK);
    }


}
